﻿using System;
using wojilu.Apps.Qycms.Domain;
using wojilu.Members.Interface;
using wojilu.Members.Sites.Domain;
using wojilu.Members.Sites.Service;
using wojilu.Members.Users.Domain;
using wojilu.Web.Controller.Common;
using wojilu.Web.Mvc.Attr;

namespace wojilu.Web.Controller.Admin.Qycms
{
    public class ModelController : BaseController
    {
        public virtual IAdminLogService<SiteLog> logService { get; set; }

        public ModelController()
        {
            logService = new SiteLogService();
        }

        private void setpublic()
        {
            User user = ctx.viewer.obj as User;
            var modelPowerGroup = PowerGroup.findById(user.GroupId);
            bind("powergroup", modelPowerGroup);
        }

        [HttpGet, HttpPost]
        public virtual void ModelList()
        {
            SetPublic();
            setpublic();
            set("load", to(new AdminController().Load) + "?");
            set("view", to(new QycmsController().Admin_Tab_List));
            var condition = String.Empty;
            DataPage<Model> list = null;
            Int32 maxperpage = ctx.PostInt("MaxPerPage");
            Int32 page_id = ctx.PostInt("page_id") + 1;
            String limitkey = ctx.Get("limitkey");
            String limitclass = ctx.Get("limitclass");
            Int32 isclass = ctx.GetInt("isclass");
            switch (isclass)
            {
                case 1:
                    condition += " isclass = 1 ";
                    break;

                case 2:
                    condition += " isclass = 0 ";
                    break;
            }
            Int32 lockin = ctx.GetInt("lockin");
            switch (lockin)
            {
                case 1:
                    condition += " and lockin = 1 ";
                    break;

                case 2:
                    condition += " and lockin = 0 ";
                    break;
            }
            Int32 isbase = ctx.GetInt("isbase");
            switch (isbase)
            {
                case 1:
                    condition += " and isbase = 1 ";
                    break;

                case 2:
                    condition += " and isbase = 0 ";
                    break;
            }
            Int32 istsn = ctx.GetInt("istsn");
            switch (istsn)
            {
                case 1:
                    condition += " and istsn = 1 ";
                    break;

                case 2:
                    condition += " and istsn = 0 ";
                    break;
            }
            Int32 isalbum = ctx.GetInt("isalbum");
            switch (isalbum)
            {
                case 1:
                    condition += " and isalbum = 1 ";
                    break;

                case 2:
                    condition += " and isalbum = 0 ";
                    break;
            }
            Int32 isextid = ctx.GetInt("isextid");
            switch (isextid)
            {
                case 1:
                    condition += " and isextid = 1 ";
                    break;

                case 2:
                    condition += " and isextid = 0 ";
                    break;
            }
            Int32 issid = ctx.GetInt("issid");
            switch (issid)
            {
                case 1:
                    condition += " and issid = 1 ";
                    break;

                case 2:
                    condition += " and issid = 0 ";
                    break;
            }
            Int32 isfgid = ctx.GetInt("isfgid");
            switch (isfgid)
            {
                case 1:
                    condition += " and isfgid = 1 ";
                    break;

                case 2:
                    condition += " and isfgid = 0 ";
                    break;
            }
            Int32 islinkdid = ctx.GetInt("islinkdid");
            switch (islinkdid)
            {
                case 1:
                    condition += " and islinkdid = 1 ";
                    break;

                case 2:
                    condition += " and islinkdid = 0 ";
                    break;
            }
            if (strUtil.IsNullOrEmpty(limitkey)) limitkey = "id";
            if (strUtil.IsNullOrEmpty(limitclass)) limitclass = "desc";
            condition += " order by " + limitkey + " " + limitclass;
            CurrentRequest.setCurrentPage(page_id);
            list = Model.findPage(condition, maxperpage);
            if (ctx.web.postValueAll().Count == 0)
            {
                ctx.web.ResponseWrite(list.RecordCount.ToString());
                ctx.web.ResponseEnd();
            }
            bind("list", list.Results);
        }

        [HttpGet]
        public virtual void ModelAdd()
        {
            SetPublic();
            setpublic();
            target(ModelAddDo);
            set("iframename", ctx.Get("iframename"));
            set("iframeheightwindow", ctx.GetInt("iframeheightwindow"));
            set("load", to(new AdminController().Load) + "?");
            set("refalse", "1");
            set("tab", "true");
            var list = Order_Pay.find(" isclass=:i").set("i", 1).list();
            bind("list", list);
        }

        [HttpPost]
        public virtual void ModelAddDo()
        {
            Model m = new Model();
            m.lng = DefaultLng;
            m.modelname = ctx.Post("modelname");
            m.pagemax = ctx.PostInt("pagemax");
            m.tsnstyle = ctx.Post("tsnstyle");
            m.pagesylte = ctx.PostInt("pagesylte");
            m.isclass = 1;
            m.lockin = 0;
            m.isbase = ctx.PostInt("isbase");
            m.istsn = ctx.PostInt("istsn");
            m.isalbum = ctx.PostInt("isalbum");
            m.isextid = ctx.PostInt("isextid");
            m.issid = ctx.PostInt("issid");
            m.isfgid = ctx.PostInt("isfgid");
            m.islinkdid = ctx.PostInt("islinkdid");
            m.isorder = ctx.PostInt("isorder");
            m.ismessage = ctx.PostInt("ismessage");
            m.ispurview = ctx.PostInt("ispurview");
            m.addtime = DateTime.Now;
            m.opid = ctx.PostInt("opid");
            Result result = m.insert();
            var ma = Model_Att.find(" mid=0 and issys=0 order by id asc").list();
            foreach (var row in ma)
            {
                row.mid = m.Id;
                row.issys = (int)row.Id;
                row.pid = 50;
                row.islockin = 1;
                row.insert();
            }
            if (result.HasErrors)
            {
                logService.Add((User)ctx.viewer.obj, lang("modelmanage_add_log") + lang("log_extra_no"), "{Erros:'" + result.ErrorsText + "'}", "", ctx.Ip);
                ctx.web.ResponseWrite("false");
            }
            else
            {
                logService.Add((User)ctx.viewer.obj, lang("modelmanage_add_log") + lang("log_extra_ok"), "{Id:" + m.Id + ", Name:'" + m.modelname + "'}", "", ctx.Ip);
                ctx.web.ResponseWrite("true");
            }
            ctx.web.ResponseEnd();
        }

        [HttpGet]
        public virtual void ModelEdit(Int64 id)
        {
            SetPublic();
            setpublic();
            target(ModelEditDo, id);
            set("iframename", ctx.Get("iframename"));
            set("iframeheightwindow", ctx.GetInt("iframeheightwindow"));
            set("load", to(new AdminController().Load) + "?");
            Model m = Model.findById(id);
            bind("modelread", m);
            var list = Order_Pay.find(" isclass=:i").set("i", 1).list();
            bind("list", list);
        }

        [HttpPost]
        public virtual void ModelEditDo(Int64 id)
        {
            Model m = Model.findById(id);
            m.modelname = ctx.Post("modelname");
            m.pagemax = ctx.PostInt("pagemax");
            m.tsnstyle = ctx.Post("tsnstyle");
            m.pagesylte = ctx.PostInt("pagesylte");
            m.isbase = ctx.PostInt("isbase");
            m.istsn = ctx.PostInt("istsn");
            m.isalbum = ctx.PostInt("isalbum");
            m.isextid = ctx.PostInt("isextid");
            m.issid = ctx.PostInt("issid");
            m.isfgid = ctx.PostInt("isfgid");
            m.islinkdid = ctx.PostInt("islinkdid");
            m.isorder = ctx.PostInt("isorder");
            m.ismessage = ctx.PostInt("ismessage");
            m.ispurview = ctx.PostInt("ispurview");
            m.opid = ctx.PostInt("opid");
            Result result = m.update();
            if (result.HasErrors)
            {
                logService.Add((User)ctx.viewer.obj, lang("modelmanage_edit_log") + lang("log_extra_no"), "{Erros:'" + result.ErrorsText + "'}", "", ctx.Ip);
                ctx.web.ResponseWrite("false");
            }
            else
            {
                logService.Add((User)ctx.viewer.obj, lang("modelmanage_edit_log") + lang("log_extra_ok"), "{Id:" + m.Id + ", Name:'" + m.modelname + "'}", "", ctx.Ip);
                ctx.web.ResponseWrite("true");
            }
            ctx.web.ResponseEnd();
        }

        [HttpGet]
        public virtual void ModelDel(Int64 id)
        {
            Model m = Model.findById(id);
            if (m.delete() > 0)
            {
                logService.Add((User)ctx.viewer.obj, lang("modelmanage_del_log") + lang("log_extra_ok"), "{Id:" + m.Id + ", Name:'" + m.modelname + "'}", "", ctx.Ip);
                ctx.web.ResponseWrite("true");
            }
            else
            {
                logService.Add((User)ctx.viewer.obj, lang("modelmanage_del_log") + lang("log_extra_no"), "{Erros:''}", "", ctx.Ip);
                ctx.web.ResponseWrite("false");
            }
        }

        [HttpGet, HttpPost]
        public virtual void ModelAttrList(Int64 id)
        {
            SetPublic();
            setpublic();
            set("load", to(new AdminController().Load) + "?");
            var condition = String.Empty;
            DataPage<Model_Att> list = null;
            Int32 maxperpage = ctx.PostInt("MaxPerPage");
            Int32 page_id = ctx.PostInt("page_id") + 1;
            String limitkey = ctx.Get("limitkey");
            String limitclass = ctx.Get("limitclass");
            Int32 isclass = ctx.GetInt("isclass");
            switch (isclass)
            {
                case 1:
                    condition += " isclass = 1 ";
                    break;

                case 2:
                    condition += " isclass = 0 ";
                    break;
            }
            if (id > 1)
            {
                condition += " and mid = " + id;
            }
            else
            {
                condition += " and (mid = " + id + " or mid = 0 and id <=8)";
            }
            Int32 isvalidate = ctx.GetInt("isvalidate");
            switch (isvalidate)
            {
                case 1:
                    condition += " and isvalidate = 1 ";
                    break;

                case 2:
                    condition += " and isvalidate = 0 ";
                    break;
            }
            Int32 issearch = ctx.GetInt("issearch");
            switch (issearch)
            {
                case 1:
                    condition += " and issearch = 1 ";
                    break;

                case 2:
                    condition += " and issearch = 0 ";
                    break;
            }
            if (strUtil.IsNullOrEmpty(limitkey)) limitkey = "id";
            if (strUtil.IsNullOrEmpty(limitclass)) limitclass = "desc";
            condition += " order by " + limitkey + " " + limitclass;
            CurrentRequest.setCurrentPage(page_id);
            list = Model_Att.findPage(condition, maxperpage);
            if (ctx.web.postValueAll().Count == 0)
            {
                ctx.web.ResponseWrite(list.RecordCount.ToString());
                ctx.web.ResponseEnd();
            }
            bind("list", list.Results);
        }

        [HttpGet]
        public virtual void ModelAttrAdd(Int64 id)
        {
            SetPublic();
            setpublic();
            target(ModelAttrAddDo, id);
            set("iframename", ctx.Get("iframename"));
            set("iframeheightwindow", ctx.GetInt("iframeheightwindow"));
            set("load", to(new AdminController().Load) + "?");
            set("refalse", "1");
            set("mid", id);
            var list = cdb.findAll<FormType>();
            bind("list", list);
        }

        [HttpPost]
        public virtual void ModelAttrAddDo(Int64 id)
        {
            var attrname = ctx.Post("attrname").ToLower();
            var inputtype = ctx.Post("inputtype");
            var attrlenther = 0;
            Model_Att a = Model_Att.find(" attrname =:a and mid =:i").set("a", attrname).set("i", id).first();
            if (a == null)
            {
                var list = Model_Att.find(" attrname =:a").set("a", attrname).list();
                if (list.Count == 0)
                {
                    var list1 = cdb.findAll<FormType>();
                    foreach (var row in list1)
                    {
                        if (row.Key == inputtype)
                        {
                            attrlenther = row.VarLong;
                            switch (row.Key)
                            {
                                case "string":
                                case "img":
                                case "addon":
                                case "video":
                                case "select":
                                case "radio":
                                case "checkbox":
                                case "selectinput":
                                    var sql = "ALTER TABLE `ybb_document_attr` ADD `" + attrname + "` " + row.Alter + "( " + row.VarLong + " );";
                                    db.RunSql(sql);
                                    break;

                                case "text":
                                case "editor":
                                case "htmltext":
                                    sql = "ALTER TABLE `ybb_document_attr` ADD `" + attrname + "` " + row.Alter + ";";
                                    db.RunSql(sql);
                                    break;

                                case "int":
                                    sql = "ALTER TABLE `ybb_document_attr` ADD `" + attrname + "` " + row.Alter + " DEFAULT 0;";
                                    db.RunSql(sql);
                                    break;

                                case "float":
                                case "decimal":
                                    sql = "ALTER TABLE `ybb_document_attr` ADD `" + attrname + "` " + row.Alter + ";";
                                    db.RunSql(sql);
                                    break;

                                case "datetime":
                                    sql = "ALTER TABLE `ybb_document_attr` ADD `" + attrname + "` " + row.Alter + ";";
                                    db.RunSql(sql);
                                    break;
                            }
                        }
                    }
                }
                Model_Att ma = new Model_Att();
                ma.pid = 50;
                ma.mid = id;
                ma.typename = ctx.Post("typename");
                ma.typeremark = ctx.Post("typeremark");
                ma.attrname = attrname;
                ma.inputtype = inputtype;
                ma.attrvalue = ctx.Post("attrvalue");
                ma.attrsize = ctx.PostInt("attrsize");
                ma.attrrow = ctx.PostInt("attrrow");
                ma.attrlenther = attrlenther;
                ma.isvalidate = ctx.PostInt("isvalidate");
                ma.validatetext = ctx.Post("validatetext");
                ma.isclass = ctx.PostInt("isclass");
                ma.islockin = 1;
                Model_Att ma1 = Model_Att.find("mid=0 and attrname=:a").set("a", attrname).first();
                if (ma1 == null)
                {
                    ma.issys = 0;
                    ma.lockin = 0;
                }
                else
                {
                    ma.lockin = 1;
                    ma.issys = ma1.Id.ObjectToInt();
                }
                Result result = ma.insert();
                if (result.HasErrors)
                {
                    logService.Add((User)ctx.viewer.obj, lang("modelmanage_attr_add_log") + lang("log_extra_no"), "{Erros:'" + result.ErrorsText + "'}", "", ctx.Ip);
                    ctx.web.ResponseWrite("false");
                }
                else
                {
                    logService.Add((User)ctx.viewer.obj, lang("modelmanage_attr_add_log") + lang("log_extra_ok"), "{Id:" + ma.Id + ", Name:'" + ma.attrname + "'}", "", ctx.Ip);
                    ctx.web.ResponseWrite("true");
                }
            }
            else
            {
                logService.Add((User)ctx.viewer.obj, lang("modelmanage_attr_add_log") + lang("log_extra_no"), "{attrname:'" + attrname + "'}", "", ctx.Ip);
                ctx.web.ResponseWrite("false");
            }
            ctx.web.ResponseEnd();
        }

        [HttpGet]
        public virtual void ModelAttrEdit(Int64 id)
        {
            SetPublic();
            setpublic();
            target(ModelAttrEditDo, id);
            set("iframename", ctx.Get("iframename"));
            set("iframeheightwindow", ctx.GetInt("iframeheightwindow"));
            set("load", to(new AdminController().Load) + "?");
            Model_Att m = Model_Att.findById(id);
            bind("modelattrread", m);
            set("mid", ctx.GetInt("mid"));
            var list = cdb.findAll<FormType>();
            bind("list", list);
        }

        [HttpPost]
        public virtual void ModelAttrEditDo(Int64 id)
        {
            Model_Att m = Model_Att.findById(id);
            m.typename = ctx.Post("typename");
            m.typeremark = ctx.Post("typeremark");
            m.attrvalue = ctx.Post("attrvalue");
            m.isvalidate = ctx.PostInt("isvalidate");
            m.validatetext = ctx.Post("validatetext");
            m.attrsize = ctx.PostInt("attrsize");
            m.attrrow = ctx.PostInt("attrrow");
            m.issearch = ctx.PostInt("issearch");
            m.isclass = ctx.PostInt("isclass");
            Result result = m.update();
            if (result.HasErrors)
            {
                logService.Add((User)ctx.viewer.obj, lang("modelmanage_attr_edit_log") + lang("log_extra_no"), "{Erros:'" + result.ErrorsText + "'}", "", ctx.Ip);
                ctx.web.ResponseWrite("false");
            }
            else
            {
                logService.Add((User)ctx.viewer.obj, lang("modelmanage_attr_edit_log") + lang("log_extra_ok"), "{Id:" + m.Id + ", Name:'" + m.attrname + "'}", "", ctx.Ip);
                ctx.web.ResponseWrite("true");
            }
            ctx.web.ResponseEnd();
        }

        [HttpPost, HttpGet]
        public virtual void CheckAttrName()
        {
            var attrname = ctx.Post("attrname").ToLower();
            var inputtype = ctx.Get("inputtype");
            var mid = ctx.GetInt("mid");
            Model_Att a = Model_Att.find(" attrname =:a and mid =:i").set("a", attrname).set("i", mid).first();
            if (a != null)
            {
                ctx.web.ResponseWrite("false");
                ctx.web.ResponseEnd();
            }
            else
            {
                var list = Model_Att.find(" attrname =:a").set("a", attrname).list();
                if (list.Count > 0)
                {
                    foreach (var row in list)
                    {
                        if (row.inputtype == inputtype)
                        {
                            ctx.web.ResponseWrite("true");
                            ctx.web.ResponseEnd();
                            break;
                        }
                    }
                    ctx.web.ResponseWrite("false");
                }
                else
                {
                    ctx.web.ResponseWrite("true");
                }
                ctx.web.ResponseEnd();         
            }
        }

        [HttpPost]
        public virtual void ModelAttrDel()
        {
            string Ids = ctx.PostIdList("selectinfoid");
            string condition = string.Format("Id in ({0})", Ids);
            if (db.deleteBatch<Model_Att>(condition) > 0)
            {
                logService.Add((User)ctx.viewer.obj, lang("modelmanage_attr_log_del") + lang("log_extra_ok"), "{Id:" + Ids + "'}", "", ctx.Ip);
                ctx.web.ResponseWrite("true");
            }
            else
            {
                logService.Add((User)ctx.viewer.obj, lang("modelmanage_attr_log_del") + lang("log_extra_no"), "{Id:" + Ids + "'}", "", ctx.Ip);
                ctx.web.ResponseWrite("false");
            }
            ctx.web.ResponseEnd();
        }

        [HttpPost]
        public virtual void ModelAttrSort(Int64 id)
        {
            var infoid = ctx.PostIdList("infoid");
            var pid = ctx.PostIdList("pid");
            var strArray = infoid.Split(new char[] { ',' });
            var strArray1 = pid.Split(new char[] { ',' });
            for (int i = 0; i < strArray.Length; i++)
            {
                string condition = string.Format("Id = {0}", strArray[i]);
                db.updateBatch<Model_Att>("set pid=" + strArray1[i], condition);
            }
            logService.Add((User)ctx.viewer.obj, lang("modelmanage_attr_log_sort") + lang("log_extra_ok"), "{Id:" + infoid + "'}", "", ctx.Ip);
            ctx.web.ResponseWrite("true");
            ctx.web.ResponseEnd();
        }

        [HttpGet,HttpPost]
        public virtual void ModelSetting()
        {
            string Ids = ctx.PostIdList("selectinfoid");
            string condition = string.Format("Id in ({0})", Ids);
            var value = ctx.Post("value");
            var dbname = ctx.Post("dbname");
            db.updateBatch<Model>("set " + dbname + "=" + value, condition);
            if (!ctx.HasErrors)
            {
                logService.Add((User)ctx.viewer.obj, lang("modelmanage_edit_log") + lang("log_extra_ok"), "{Id:" + Ids + "'}", "", ctx.Ip);
                ctx.web.ResponseWrite("true");
            }
            else
            {
                logService.Add((User)ctx.viewer.obj, lang("modelmanage_edit_log") + lang("log_extra_no"), "{Id:" + Ids + "'}", "", ctx.Ip);
                ctx.web.ResponseWrite("false");
            }
            ctx.web.ResponseEnd();
        }

    }
}
